/*
** listener.c -- a datagram sockets "server" demo
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <vector>
using namespace std;

#define MYPORT 9998	// the port users will be connecting to

#define MAXBUFLEN 1024

int main(int argc, char *argv[])
{
	srand(time(NULL));
	int sockfd, percent, test_rand;
	int counter = 0;
	int flag = 0;
	struct sockaddr_in my_addr;	// my address information
	struct sockaddr_in their_addr; // connector's address information
	socklen_t addr_len;
	int numbytes;
	char buf[MAXBUFLEN];
	char msg[MAXBUFLEN];
	vector<int> msgVect;

	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	int yes=1;


	// lose the pesky "Address already in use" error message
	if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1)
	{
  	  	perror("setsockopt");
    		exit(1);
	} 
	
	/* Check if enough arguments have been given */
	if (argc != 2) {
		fprintf(stderr,"usage: percent");
		exit(1);
	}
	
	/* Test percentage */
	percent = atoi(argv[1]);
	if(percent < 0 || percent > 100)
	{
		fprintf(stderr, "Invalid percent number.\n");
		exit(1);
	}


	my_addr.sin_family = AF_INET;		 // host byte order
	my_addr.sin_port = htons(MYPORT);	 // short, network byte order
	my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
	memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);

	if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) {
		perror("bind");
		exit(1);
	}

	addr_len = sizeof their_addr;
	while(1)
	{
		test_rand = (rand() % 100) + 1;
		if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
			(struct sockaddr *)&their_addr, &addr_len)) == -1) {
			perror("recvfrom");
			exit(1);
		}
		int buffer = atoi(buf);
		/* Test whether or not to drop message */
		if(test_rand <= percent) {
		  	/* Checks vector for duplicates */
			for(int i = 0; i < msgVect.size(); i++){
				if(msgVect[i] == buffer)
					flag = 1;
			}
			
			/* Prints duplicate message if flag is set */
			if(flag == 1){
				printf("\nDuplicate Message\n");
				//printf("ACK: %d\n", buffer);
				flag = 0;
			}
			
			/* If not duplicate, push into vector */
			else{
				msgVect.push_back(buffer);
				printf("\nACK: %d\n", buffer);
				sendto(sockfd, buf, strlen(buf), 0,(struct sockaddr *)&their_addr, sizeof their_addr);
				//counter++; //counter measures how many messages acknowledged
			}
		}
		else{
			//printf("\nrand num: %d \t percent: %d \n", test_rand, percent);
			//printf("message discarded\n");
		}
	}

	close(sockfd);

	return 0;
}
